<template>
  <div>
    <div v-title data-title="十分读书" class="BuyVip" v-if="dataComplete">
      <!--<Marquee top="5" left="5" :marqueeList="loop_buys" ></Marquee>-->
      <PayState v-if="payState" v-on:hide="Popuphide" v-on:to="Popupgo"></PayState>
      <div class="content" v-html="Buys" :style="{'padding-bottom':bottom+'px'}">
      </div>
      <Inform v-on:go="gos"></Inform>
      <div class="BuyFooter" ref="foot" v-if="paylist.length>1">
        <ul>
          <li v-for="(a,i) in paylist" v-if="i<2">
            <div class="test">
              <p style=" display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;">
                <span class="fasr-span"><i class="iconfont icon-icon-test" style=""></i>{{a.actual_price}}</span>
                <s>&yen;{{a.original_price}}</s>
                <span class="nth-span">{{a.goods_unit_name}}</span><span class="nth-span" style="color: #fd2840;">{{a.goods_unit}}</span>
              </p>
              <p style="display: -webkit-box;
     -webkit-box-orient: vertical;
     -webkit-line-clamp: 1;
    overflow: hidden;">{{a.discount_desc}}</p>
            </div>
            <div class="btnx">
              <btn :obj="a.btnStyle" :text="a.btnText" v-on:statr="go(a)"></btn>
            </div>
          </li>
        </ul>
      </div>
      <CollectPopup v-if="Popup" :img="erweiam" :istrue="Popup" v-on:hide="Popuphide"></CollectPopup>
      <div class="buyfoot" ref="foot" v-if="paylist.length===1">
        <div class="record-time" v-if="loop_timestamp!== -1">限时优惠，仅剩
          <div class="time-container">00</div>
          时
          <div class="time-container">{{recordMin}}</div>
          分
          <div class="time-container">{{recordSec}}</div>
          秒
          <div class="time-container">{{recordMs}}</div>
        </div>
        <div class="doc" style=" display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;">
          <!--<i class="iconfont icon-xiaoxi"></i>-->
          <span style="font-weight: 500;font-size:2.4rem;color: #f03d38; "><i class="iconfont icon-icon-test"></i>{{paylist[0].actual_price}}</span>
          <s>原价￥{{paylist[0].original_price}}</s>
          <span>{{paylist[0].goods_unit_name}}</span>
          <span>{{paylist[0].discount_desc}}</span>
        </div>
        <div class="btnx">
          <btn :obj="paylist[0].btnStyle" :text="paylist[0].btnText" v-on:statr="go(paylist[0])"></btn>
        </div>
      </div>
    </div>
    <div v-if="!dataComplete">
      正在加载数据....
    </div>
  </div>
</template>

<script>
  import btn from '../../components/btn/index'
  import Inform from '../../components/buyInform/index'
  import CollectPopup from '../../components/BuyPopup/index'
  import PayState from '../../components/PayState/index'
  import Login from '../../login/index'
  import {Indicator, Toast} from 'mint-ui'
  // import Marquee from '../../components/Marquee/Index'

  export default {
    name: 'index',
    data: function () {
      return {
        dataComplete:false,
        btnstyle: {
          backgroundColor: '#fd2840',
          height: '4,5rem',
          padding: '0 1rem',
          fontSize: '1.8rem',
          color: '#fff',
          borderRadius: '.3rem',
          opacity: 1
        },
        btntext: '',
        btnstyles: {
          width: '95%',
          backgroundColor: '#fd2840',
          height: '4.5rem',
          border: '1px solid #fd2840',
          padding: '0 1rem',
          fontSize: '1.8rem',
          color: '#fff',
          borderRadius: '.3rem',
          opacity: 1
        },
        group_url: "",
        style: {
          backgroundColor: '#fff',
          height: '4.5rem',
          border: '1px solid #fd2840',
          padding: '0 1rem',
          fontSize: '1.8rem',
          color: '#fd2840',
          borderRadius: '.3rem',
          opacity: 1
        },
        btntexts: '立即续费',
        Buys: '',
        paylist: [
          {
            original_price: 0,
            goods_unit_name: ''
          }
        ],
        num: 0,
        is_vip: 0,
        erweiam: 'https://staticreading.qingclass.com/course/20190129/4134b1b7bf014c4fa09afa04daf589ef.jpeg',
        Popup: false,
        data: {
          page_index: 1,
          share_id: this.$route.query.share_id || -1,
          share_token: this.$route.query.share_token || -1,
          goods_id: this.$route.query.goods_id || -1
        },
        subscribe: 0,
        Paydate: {},
        payState: false,
        bottom: 70,
        recordTime: 0,
        recordMin: '',
        recordSec: '',
        recordMs: '',
        loop_buys: [],
        loop_timestamp: -1,
        can_buy: 0
      }
    },
    mounted: function () {
      var logger = this.$axios.logger()
      logger.push('user_id', this.$Login.oauth_token.user_id)
      logger.push('page_url', window.location.href);
      logger.push('user_action', 1);
      logger.push('platform_id', 5);
      logger.push('platform_user_id', this.$Login.Vip_token.vip_user_id);
      logger.push('share_id', this.$route.query.share_id || -1);
      logger.push('share_token', this.$route.query.share_token || '-1');
      logger.logger();
      this.update(this.data)
      // 如果local中没有起始时间，则记录
      if (!window.localStorage.getItem('recordTime')) {
        window.localStorage.setItem('recordTime', new Date().getTime() + '')
      }
      this.recordTime = new Date().getTime() - parseInt(window.localStorage.getItem('recordTime'))
    },
    methods: {
      update: function (data) {
        this.$axios.goods_list(data).then(res => {
          this.dataComplete  = true
          this.Buys = this.$Mate.qingReads(res.data.qing_data.desc)
          this.is_vip = res.data.qing_data.is_vip
          this.group_url = res.data.qing_data.group_url
          this.subscribe = res.data.qing_data.subscribe
          // this.loop_buys = res.data.qing_data.loop_buys
          // this.loop_timestamp = res.data.qing_data.loop_timestamp
          // 30分钟倒计时
          // this.SetTime((this.loop_timestamp / 100) - (this.recordTime % (this.loop_timestamp)) / 100)
          var _this = this
          var can_buys = res.data.qing_data.can_buys
          var list = res.data.qing_data.list
          list.forEach((item, i) => {
            item.is_Buy = can_buys[i]
            item.pay_mode_id = res.data.qing_data.pay_mode_id || 1
            if (item.goods_unit_name.indexOf('（') !== -1) {
              var name = item.goods_unit_name
              item.goods_unit = '（' + name.split('（')[1]
              item.goods_unit_name = name.split('（')[0]
            }
            if (can_buys[i] === 0) {
              item.btnText = '您已购买'
              if (list.length === 1) {
                item.btnStyle = {
                  width: '95%',
                  backgroundColor: '#E6e6e6',
                  height: '4.5rem',
                  border: '1px solid #E6e6e6',
                  padding: '0 1rem',
                  fontSize: '1.8rem',
                  color: '#fff',
                  borderRadius: '.3rem',
                  opacity: 1
                }
              } else if (i === 0) {
                item.btnStyle = {
                  backgroundColor: '#fff',
                  height: '4.5rem',
                  border: '1px solid #E6e6e6',
                  padding: '0 1rem',
                  fontSize: '1.8rem',
                  color: '#E6e6e6',
                  borderRadius: '.3rem',
                  opacity: 1
                }
              } else {
                item.btnStyle = {
                  backgroundColor: '#E6e6e6',
                  height: '4.5rem',
                  border: '1px solid #E6e6e6',
                  padding: '0 1rem',
                  fontSize: '1.8rem',
                  color: '#fff',
                  borderRadius: '.3rem',
                  opacity: 1
                }
              }
            } else if (can_buys[i] === 1) {
              if (_this.is_vip === 0) {
                if (item.discount_desc.indexOf('|') !== -1) {
                  item.desc = item.discount_desc
                  item.btnText = item.desc.split('|')[1]
                  item.discount_desc = item.desc.split('|')[0]
                } else {
                  item.btnText = '立即购买'
                }
              } else {
                if (item.discount_desc.indexOf('|') !== -1) {
                  item.desc = item.discount_desc
                  // item.btnText = item.desc.split('|')[1]
                  item.discount_desc = item.desc.split('|')[0]
                }
                item.btnText = '立即续费'
              }
              if (list.length === 1) {
                item.btnStyle = {
                  width: '95%',
                  backgroundColor: '#fd2840',
                  height: '4.5rem',
                  border: '1px solid #fd2840',
                  padding: '0 1rem',
                  fontSize: '1.8rem',
                  color: '#fff',
                  borderRadius: '.3rem',
                  opacity: 1
                }
              } else if (i === 0) {
                item.btnStyle = {
                  backgroundColor: '#fff',
                  height: '4.5rem',
                  border: '1px solid #fd2840',
                  padding: '0 1rem',
                  fontSize: '1.8rem',
                  color: '#fd2840',
                  borderRadius: '.3rem',
                  opacity: 1
                }
              } else {
                item.btnStyle = {
                  backgroundColor: '#fd2840',
                  height: '4,5rem',
                  padding: '0 1rem',
                  fontSize: '1.8rem',
                  color: '#fff',
                  borderRadius: '.3rem',
                  opacity: 1
                }
              }
            }
          })
          console.log(list)
          this.paylist = list
          setTimeout(() => {
            _this.bottom = _this.$refs.foot.offsetHeight + 20
          }, 500)
        })
      },
      go: function (a) {
        //不可购买无法点击
        if (a.is_Buy === 1) {
          this.data.goods_unit_id = a.goods_unit_id
          this.data.pay_mode_id = a.pay_mode_id || 1
          this.Paydetails(this.data)
        } else {
          Toast({
            message: '您已购买',
            iconClass: 'iconfont icon-bangdingshibai',
            duration: 2000
          })
        }
        // sessionStorage.setItem('Details', JSON.stringify(this.data))
        // this.$router.push({
        //   name: 'Details'
        // })
      },
      Paydetails: function (data) {
        this.$axios.order(data).then(res => {
          this.items = res.data.qing_data
          this.data.actual_price = res.data.qing_data.actual_price
          this.data.leave_msg = ''
          this.post_order()
        })
      },
      post_order: function () {
        if (this.num === 0) {
          ++this.num
        } else {
          return
        }
        var _this = this
        this.$axios.post_order(this.data).then(res => {
          var str = {
            order_id: res.data.qing_data.wx_pay_info.order_id,
            order_type: res.data.qing_data.wx_pay_info.order_type,
            pay_mode_id: res.data.qing_data.wx_pay_info.pay_mode_id
          }
          var obj = {
            timeStamp: res.data.qing_data.wx_pay_info.pay_parameters.timeStamp,
            appId: res.data.qing_data.wx_pay_info.pay_parameters.appId,
            nonceStr: res.data.qing_data.wx_pay_info.pay_parameters.nonceStr,
            package: res.data.qing_data.wx_pay_info.pay_parameters.pkg,
            paySign: res.data.qing_data.wx_pay_info.pay_parameters.paySign,
            pkg: res.data.qing_data.wx_pay_info.pay_parameters.pkg,
            signType: res.data.qing_data.wx_pay_info.pay_parameters.signType,
          }
          this.$wx.WXPay(obj, res => {
            _this.num = 0
            if (res === 'get_brand_wcpay_request:ok') {
              Indicator.open({
                text: '正在查询支付结果',
                spinnerType: 'fading-circle'
              })
              setTimeout(() => {
                _this.payment_status(str)
              }, 500)
            } else if (res === 'get_brand_wcpay_request:cancel') {
              _this.payState = true
              // Toast({
              //   message: '支付失败',
              //   iconClass: 'iconfont icon-bangdingshibai',
              //   duration: 3000
              // })
            } else if (res === 'get_brand_wcpay_request:fail') {
              _this.payState = true
              // Toast({
              //   message: '支付失败',
              //   iconClass: 'iconfont icon-bangdingshibai',
              //   duration: 3000
              // })
            }
          })
        })
      },
      payment_status: function (data) {
        this.$axios.inspect(data).then(res => {
          this.num = 0
          Indicator.close()
          if (res.data.qing_code !== 100) {
            return Toast({
              message: res.data.qing_text,
              iconClass: 'iconfont icon-bangdingshibai',
              duration: 3000
            })
          }
          if (res.data.qing_data.is_vip) {
            this.$Login.Vip_token.reading_vip_state = res.data.qing_data.is_vip
            Login.Vip_token = this.$Login.Vip_token
            localStorage.setItem('Vip_token', JSON.stringify(this.$Login.Vip_token))
          }
          if (res.data.qing_data.vip_user_id) {
            this.$Login.Vip_token.vip_user_id = res.data.qing_data.vip_user_id
            this.$Login.Vip_token.reading_vip_state = res.data.qing_data.is_vip
            this.$Login.Vip_token.vip_token1 = res.data.qing_data.vip_token1
            this.$Login.Vip_token.vip_token2 = res.data.qing_data.vip_token2
            Login.Vip_token = this.$Login.Vip_token
            localStorage.setItem('Vip_token', JSON.stringify(this.$Login.Vip_token))
          }
          if (res.data.qing_data.pay_success_img) {
            this.$router.push({
              name: 'PayResults',
              query: {
                img: res.data.qing_data.pay_success_img || 'img'
              }
            })
          } else {
            Toast({
              message: '没有图片：：：' + JSON.stringify(res.data.qing_data),
              iconClass: 'iconfont icon-bangdingshibai',
              duration: 3000
            })
            // alert('没有图片：：：' + JSON.stringify(res.data.qing_data))
          }
        })
      },
      gos: function (str) {
        if (this.subscribe === 1) {
          this.$router.push({
            name: 'Collection',
            query: this.$route.query
          })
        } else {
          this.Popup = true
        }
      },
      Popupgo: function (str) {
        this.payState = false
        if (str === 1) {
          window.location.href = this.group_url
        } else if (str === 2) {
          this.post_order()
        }
      },
      Popuphide: function () {
        this.Popup = false
        this.payState = false
      },
      // 传递100倍的毫秒值
      SetTime: function (S) {
        var timer = null
        var t = S
        var m = 0
        var s = 0
        var ms = 0
        var _this = this
        if (S === 0) {

        } else {
          m = Math.floor(t / 10 / 60 % 60)
          m < 10 && (m = '0' + m)
          s = Math.floor(t / 10 % 60)
          s < 10 && (s = '0' + s)
          ms = Math.floor(t % 10)
          ms < 10 && (ms = '0' + ms)

          function countDown() {
            ms--
            ms < 10 && (ms = '0' + ms)
            if (ms.length >= 3) {
              ms = '0' + 9
              s = (Number(s) - 1)
              s < 10 && (s = '0' + s)
            }
            if (s.length >= 3) {
              s = 59
              m = (Number(m) - 1)
              m < 10 && (m = '0' + m)
            }
            if (m.length >= 3) {
              window.clearInterval(timer)
              _this.SetTime(_this.loop_timestamp / 100)
            }
            _this.recordMin = m
            _this.recordSec = s
            _this.recordMs = ms
          }

          timer = window.setInterval(countDown, 100)
        }
      }
    },
    components: {
      btn,
      Inform,
      CollectPopup,
      PayState,
      // Marquee
    }
  }
</script>

<style scoped>
  @import '../../assets/css/views/BuyVip/index.css';
</style>
